<template>
  <el-scrollbar class="hhd-menu-vertical hhd-side-menu">
    <el-menu
      background-color="rgb(0, 21, 41)"
      text-color="rgb(183, 183, 183)"
      active-text-color="#79bbff"
      :mode="mode" @select="menuSelect"
      :default-active="defaultActive">
      <template v-for="item in actuallyMenus">
        <template v-if="item.children && item.children.length > 0">
          <SubMenus :mode="mode" :menu-item="item" :index="item.path"></SubMenus>
        </template>
        <template v-else>
          <el-menu-item :mode="mode" :index="item.path">{{ item.name }}</el-menu-item>
        </template>
      </template>
    </el-menu>
  </el-scrollbar>
</template>

<script>
import './menu.css';
import {mapGetters} from 'vuex';
import SubMenus from '@/components/AppMenu/SubMenus.vue';
import {findItemFromTrees, treesForeach} from '@/utils/CommonUtils';

export default {
  name: 'AppMenu',
  components: {
    SubMenus
  },
  props: {
    mode: {
      type: String,
      default: 'vertical',
    },
    menus: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      defaultActive: undefined
    };
  },
  mounted() {
  },
  methods: {
    menuSelect(key, keyPath) {
      let trees = this.actuallyMenus;
      let item = findItemFromTrees(trees, key, 'path');
      this.$windowManager.openWithMenu(item);
    },
    resolveActive(fullPath) {
      let res = undefined;
      treesForeach(this.actuallyMenus, (node) => {
        if (node.path === '/') {
          res = node.path;
          return;
        }
        if (fullPath.startsWith(node.path)) {
          res = node.path;
        }
      });
      return res;
    },
  },
  computed: {
    ...mapGetters('app', {
      permissionMenus: 'menus'
    }),
    actuallyMenus() {
      return [...this.menus, ...this.permissionMenus];
    },
  },
  watch: {
    '$route.path': {
      handler(toPath, fromPath) {
        console.log(this.defaultActive = this.resolveActive(this.$route.fullPath));
      },
      deep: true, // 深度监听
      immediate: true, // 第一次初始化渲染就可以监听到
    }
  }
};
</script>
